/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.yokeyword.sample.demo_flow.adapter;

import me.yokeyword.sample.ResourceTable;
import me.yokeyword.sample.entity.Article;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * HomeFraction  Adapter
 */
public class HomeAdapter extends BaseItemProvider {
    private List<Article> mItems = new ArrayList<>();
    private ListContainer.ItemClickedListener mClickListener;
    private Context myContext;

    public HomeAdapter(Context ctxt) {
        myContext = ctxt;
    }

    public void setDatas(List<Article> items) {
        mItems.clear();
        mItems.addAll(items);
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Object getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public String getTitle(int i) {
        return mItems.get(i).getTitle();
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Article article = mItems.get(i);
        Component container = LayoutScatter.getInstance(myContext).parse(ResourceTable.Layout_layout_item_home, null, false);
        Text tcTitle = (Text) container.findComponentById(ResourceTable.Id_tv_title);
        Text tcContent = (Text) container.findComponentById(ResourceTable.Id_tv_content);
        tcTitle.setText(article.getTitle());
        tcTitle.setTextColor(Color.BLACK);
        tcContent.setText(article.getContent());
        tcContent.setTextColor(Color.BLACK);
        container.setClickedListener(component1 -> mClickListener.onItemClicked(null, null, i, i));
        return container;
    }

    public void setClickListener(ListContainer.ItemClickedListener mClickListener) {
        this.mClickListener = mClickListener;
    }
}

